package org.apache.solr.dataimport.handler.scheduler;

import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApplicationListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory
			.getLogger(ApplicationListener.class);
	
	private Thread autoReloadThread = null;

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		if (autoReloadThread != null) {
			autoReloadThread.interrupt();
			autoReloadThread = null;
		}
		destoryTimer(servletContext);
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		final ServletContext servletContext = servletContextEvent.getServletContext();
		final String autoDeltaImportConfPath = servletContext.getInitParameter("autoDeltaImportConfPath");
		final SolrDataImportProperties p = new SolrDataImportProperties(autoDeltaImportConfPath);
		createTimer(servletContext, p);
		autoReloadThread = new Thread(new Runnable(){
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(Long.parseLong(p.getProperty("autoReload")) * 1000);
					} catch (Exception e) {
						logger.error("thread sleep failed!", e);
					}
					if (p.isModified()) {
						logger.info("reload dataimport.properties!");
						p.loadProperties(true);
						createTimer(servletContext, p);
					}
				}
			}
		});
		autoReloadThread.setDaemon(true);
		autoReloadThread.start();
	}
	
	private void createTimer(ServletContext servletContext, SolrDataImportProperties p) {
		Timer timer = createTimer(p);
		if (timer != null) {
			destoryTimer(servletContext);
			// save the timer in context
			servletContext.setAttribute("timer", timer);
		}
	}
	
	private Timer createTimer(SolrDataImportProperties p) {
		try {
			// create the timer and timer task objects
			Timer timer = new Timer();
			HttpPostScheduler task = new HttpPostScheduler(p);
			// get our interval from HTTPPostScheduler
			int interval = task.getIntervalInt();
			interval = 1000 * 60 * interval;
			// schedule the task
			timer.scheduleAtFixedRate(task, interval, interval);
			return timer;
		} catch (Exception e) {
			if (e.getMessage().endsWith("disabled")) {
				logger.info("Schedule disabled");
			} else {
				logger.error("Problem initializing the scheduled task: ", e);
			}
			return null;
		}
	}
	
	private void destoryTimer(ServletContext servletContext) {

		// get our timer from the context
		Timer timer = (Timer) servletContext.getAttribute("timer");

		// cancel all active tasks in the timers queue
		if (timer != null)
			timer.cancel();

		// remove the timer from the context
		servletContext.removeAttribute("timer");
	}

}